package com.masterclient.app.modules.search;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.eoner.baselib.enums.FCPageViewState;
import com.eoner.baselib.widget.empty.FCPageStateView;
import com.eoner.baselibrary.bean.firstpager.SearchConditionBean;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.masterclient.app.BaseFragment;
import com.masterclient.app.R;
import com.masterclient.app.modules.goods.adapter.CommonGoodsRecyclerAdapter;
import com.masterclient.app.modules.search.contract.GoodResultContract;
import com.masterclient.app.modules.search.contract.GoodResultPresenter;
import com.masterclient.app.widget.StaggeredGoodsItemDecoration;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 作者：sean
 * 创建时间：2017/6/23 17:42
 * 功能说明：搜索商品结果
 */

public class SearchGoodResultFragment extends BaseFragment<GoodResultPresenter> implements GoodResultContract.View {

    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.tv_default)
    TextView tvDefault;
    @BindView(R.id.tv_sale_volume)
    TextView tvSaleVolume;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_price_icon)
    ImageView tvPriceIcon;
    @BindView(R.id.tv_filt)
    TextView tvFilt;
    @BindView(R.id.tv_filt_layout)
    LinearLayout tvFiltLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.iv_back_top)
    ImageView ivBackTop;
    @BindView(R.id.ll_select)
    LinearLayout llSelect;

    private CommonGoodsRecyclerAdapter searchGoodRecyclerAdapter;

    private int totalRow;
    private int page = 1;
//    private List<ProductBean> goodList;
    private SearchGoodBean.DataBean dataBean;
    String keyword,sort = "new";
//    private View footView;

    SearchConditionBean conditionBean;
    private boolean first = true;
    FCPageStateView emptyView;
    private StaggeredGridLayoutManager layoutManager;

    public static SearchGoodResultFragment getInstance(@NonNull String keyword) {
        Bundle bundle = new Bundle();
        bundle.putString("keyword",keyword);
        SearchGoodResultFragment searchGoodResultFragment = new SearchGoodResultFragment();
        searchGoodResultFragment.setArguments(bundle);
        return searchGoodResultFragment;
    }

    @Override
    protected View getRootView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_search_good_result, null);
    }

    @Override
    protected void initOnlyOnce() {
        Bundle bundle = getArguments();
        if(bundle != null){
            keyword = bundle.getString("keyword");
        }
//        goodList = new ArrayList<>();


//        footView = View.inflate(mContext,R.layout.view_foot_view,null);
//        recyclerView.setLayoutManager(new GridLayoutManager(mContext, 2));
        layoutManager =
                new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(null);

        searchGoodRecyclerAdapter = new CommonGoodsRecyclerAdapter();
        searchGoodRecyclerAdapter.setStrings("搜索结果页面","","",keyword,((SearchResultActivity)getActivity()).search_type);
        recyclerView.setAdapter(searchGoodRecyclerAdapter);
        searchGoodRecyclerAdapter.bindToRecyclerView(recyclerView);
        emptyView = new FCPageStateView(getActivity());
        emptyView.setViewState(FCPageViewState.PAGE_STATE_NO_DATA,R.mipmap.icon_empty_result,"换个词，说不定可行");
        emptyView.setVisibility(View.GONE);
        searchGoodRecyclerAdapter.setEmptyView(emptyView);
//        searchGoodRecyclerAdapter.setFooterView(footView);
        recyclerView.addItemDecoration(new StaggeredGoodsItemDecoration(ScreenUtils.dp2px(10)));

        conditionBean = new SearchConditionBean();
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
//                if(goodList!=null){
//                    goodList.clear();
//                    emptyView.setVisibility(View.GONE);
//                    searchGoodRecyclerAdapter.notifyDataSetChanged();
//                }
//                searchGoodRecyclerAdapter.setEnableLoadMore(true);
                searchNewCondition();
            }
        });

        searchGoodRecyclerAdapter.setOnLoadMoreListener(()->{
//            if(goodList != null && goodList.size()<totalRow){
                setSelectTag();
                mPresenter.searchGoodList(conditionBean.getAttributes(), conditionBean.getBrand_ids(), conditionBean.getCids(), conditionBean.getStart_price(), conditionBean.getEnd_price(), keyword, page + "", PAGE_SIZE, sort,conditionBean.getPromotion_type());
//            }

        },recyclerView);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
//                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
//                int firstVisibleItemPosition = manager.findFirstVisibleItemPosition();
                StaggeredGridLayoutManager manager = (StaggeredGridLayoutManager) recyclerView.getLayoutManager();
                int[] first = new int[manager.getSpanCount()];
                manager.findFirstCompletelyVisibleItemPositions(first);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && (first[0] == 1 || first[1] == 1)) {
                    manager.invalidateSpanAssignments();
                }

                int[] firstVisibleItemPosition = new int[manager.getSpanCount()];
                manager.findFirstVisibleItemPositions(firstVisibleItemPosition);
                if(ivBackTop!=null) {
                    if (firstVisibleItemPosition[0] <= 7) {
                        ivBackTop.setVisibility(View.INVISIBLE);
                    } else {
                        ivBackTop.setVisibility(View.VISIBLE);
                    }
                }
//                if(ivBackTop!=null){
//                     if (firstVisibleItemPosition == 0) {
//                        ivBackTop.setVisibility(View.INVISIBLE);
//                    } else {
//                        ivBackTop.setVisibility(View.VISIBLE);
//                    }
//                }



//                } else if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {//拖动中
//                    ivBackTop.setVisibility(View.INVISIBLE);
//                }
            }
        });

        ivBackTop.setOnClickListener(v->{
            recyclerView.scrollToPosition(0);
            ivBackTop.setVisibility(View.GONE);
        });
    }

    @Override
    protected void initView(View mRootView) {
        if(first){
            searchNewCondition();
        }
        super.initView(mRootView);
    }

    @OnClick({R.id.tv_filt_layout}) void openDrawer(){
        if(onOpenDrawerListerner != null){
            onOpenDrawerListerner.onOpenListerner(dataBean);
        }
    }

    @SuppressWarnings("ResourceType")

    @OnClick({R.id.tv_default,R.id.tv_sale_volume,R.id.tv_price,R.id.tv_price_icon}) void onClick(View view){
        switch (view.getId()){
            case R.id.tv_default:

                if("new".equals(sort)){
                }else if("hot".equals(sort)){
                    tvDefault.setTextColor(getResources().getColor(R.color.color_333333));
                    tvSaleVolume.setTextColor(getResources().getColor(R.color.textColor_999));
                    sort = "new";
                    searchNewCondition();
                }else if("price_desc".equals(sort)||"price_asc".equals(sort)){
                    tvPriceIcon.setImageResource(R.mipmap.paixu_icon);
//                    Drawable nav_up=getResources().getDrawable(R.mipmap.paixu_icon);
//                    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
//                    tvPrice.setCompoundDrawables(null,null,nav_up,null);
                    tvPrice.setTextColor(getResources().getColor(R.color.textColor_999));
                    tvDefault.setTextColor(getResources().getColor(R.color.color_333333));
                    sort = "new";
                    searchNewCondition();
                   }

                break;
            case R.id.tv_sale_volume:
                if("hot".equals(sort)) return;

                if("new".equals(sort)){
                    tvSaleVolume.setTextColor(getResources().getColor(R.color.color_333333));
                    tvDefault.setTextColor(getResources().getColor(R.color.textColor_999));
                    sort = "hot";
                    searchNewCondition();
                }else if("hot".equals(sort)){

                }else if("price_desc".equals(sort)||"price_asc".equals(sort)){
                    tvPriceIcon.setImageResource(R.mipmap.paixu_icon);
//                    Drawable nav_up=getResources().getDrawable(R.mipmap.paixu_icon);
//                    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
//                    tvPrice.setCompoundDrawables(null,null,nav_up,null);
                    tvSaleVolume.setTextColor(getResources().getColor(R.color.color_333333));
                    tvPrice.setTextColor(getResources().getColor(R.color.textColor_999));
                    sort = "hot";
                    searchNewCondition();
                }

                break;
            case R.id.tv_price_icon:
            case R.id.tv_price:

                if("new".equals(sort)){
                    sort = "price_desc";
                    tvSaleVolume.setTextColor(getResources().getColor(R.color.textColor_999));
                    tvDefault.setTextColor(getResources().getColor(R.color.textColor_999));
                    tvPrice.setTextColor(getResources().getColor(R.color.color_333333));
                    tvPriceIcon.setImageResource(R.mipmap.paixu_down_icon);
//                    Drawable nav_up=getResources().getDrawable(R.mipmap.paixu_down_icon);
//                    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
//                    tvPrice.setCompoundDrawables(null,null,nav_up,null);
                }else if("hot".equals(sort)){
                    sort = "price_desc";
                    tvSaleVolume.setTextColor(getResources().getColor(R.color.textColor_999));
                    tvDefault.setTextColor(getResources().getColor(R.color.textColor_999));
                    tvPrice.setTextColor(getResources().getColor(R.color.color_333333));
                    tvPriceIcon.setImageResource(R.mipmap.paixu_down_icon);
//                    Drawable nav_up=getResources().getDrawable(R.mipmap.paixu_down_icon);
//                    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
//                    tvPrice.setCompoundDrawables(null,null,nav_up,null);
                }else if("price_desc".equals(sort)){
                    sort = "price_asc";
                    tvPriceIcon.setImageResource(R.mipmap.paixu_top_icon);
//                    Drawable nav_up=getResources().getDrawable(R.mipmap.paixu_top_icon);
//                    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
//                    tvPrice.setCompoundDrawables(null,null,nav_up,null);
                }else if("price_asc".equals(sort)){
                    sort = "price_desc";
                    tvPriceIcon.setImageResource(R.mipmap.paixu_down_icon);
//                    Drawable nav_up=getResources().getDrawable(R.mipmap.paixu_down_icon);
//                    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
//                    tvPrice.setCompoundDrawables(null,null,nav_up,null);
                }
                searchNewCondition();
                break;
        }
    }

    private void searchNewCondition() {
        page = 1;
//        if (goodList == null){
//            goodList = new ArrayList<>();
//        }else {
//            goodList.clear();
//        }
        searchGoodRecyclerAdapter.notifyDataSetChanged();
        recyclerView.scrollToPosition(0);
//        footView.setVisibility(View.GONE);
        mPresenter.searchGoodList(conditionBean.getAttributes(), conditionBean.getBrand_ids(), conditionBean.getCids(), conditionBean.getStart_price(), conditionBean.getEnd_price(), keyword, page + "", PAGE_SIZE, sort,conditionBean.getPromotion_type());
    }

    public void searchNewKeyWord(String keyword){
        this.first = true;
        this.keyword = keyword;
        searchNewCondition();
    }

    public void setNewKeyWord(String keyword){
        this.first = true;
        this.keyword = keyword;
    }



    @Override
    public void showSearchGood(SearchGoodBean.DataBean dataBeen) {
        this.dataBean  = dataBeen;

        if(swipeRefreshLayout.isRefreshing()){
            swipeRefreshLayout.setRefreshing(false);
        }
        searchGoodRecyclerAdapter.loadMoreComplete();

        searchGoodRecyclerAdapter.setStrings("搜索结果页面","","",keyword,((SearchResultActivity)getActivity()).search_type);
        totalRow = Integer.valueOf(dataBeen.getSh_total());
//        if (dataBeen.getSh_products() != null) {
//            if(goodList == null){
//                goodList = new ArrayList<>();
//            }
//            goodList.addAll(dataBeen.getSh_products());
//        }
//        if(goodList==null||goodList.size()<=0){
        emptyView.setVisibility(page==1&&(dataBeen.getSh_products() == null
                || dataBeen.getSh_products().size() == 0)?View.VISIBLE:View.GONE);

//            llSelect.setVisibility(View.GONE);
//        }else {
//            llSelect.setVisibility(View.VISIBLE);
//        }
//        searchGoodRecyclerAdapter.setNewData(goodList);
//        int start = goodList.size();
        if (page == 1){
            searchGoodRecyclerAdapter.setNewData(dataBeen.getSh_products());
        }else {
            searchGoodRecyclerAdapter.addData(dataBeen.getSh_products());
//            searchGoodRecyclerAdapter.addData(dataBeen.getSh_products());
//            searchGoodRecyclerAdapter.notifyItemRangeInserted(goodList.size() - dataBeen.getSh_products().size(), dataBeen.getSh_products().size());
        }




        if(dataBeen == null||dataBeen.getSh_products()==null||
                dataBeen.getSh_products().size()<=0|| "0".equals(dataBeen.getSh_has_more())) {
            searchGoodRecyclerAdapter.setEnableLoadMore(false);
//            footView.setVisibility(View.VISIBLE);
        }else {
//            footView.setVisibility(View.GONE);
        }

        ++page;

        if(onOpenDrawerListerner!=null){
            onOpenDrawerListerner.onRefreshCondition(dataBeen,first);
            if(first){
                first = false;
            }
        }
    }

    public void searchGoods(SearchConditionBean searchConditionBean){
        conditionBean = searchConditionBean;
        setSelectTag();
        searchNewCondition();
//        mPresenter.searchGoodList(conditionBean.getAttributes(), conditionBean.getBrand_ids(), conditionBean.getCids(), conditionBean.getStart_price(), conditionBean.getEnd_price(), keyword, "1", PAGE_SIZE, sort,conditionBean.getPromotion_type());
    }

    private void setSelectTag() {
        if(!TextUtils.isEmpty(conditionBean.getStart_price())||
                !TextUtils.isEmpty(conditionBean.getEnd_price())||
                (conditionBean.getBrand_ids()!=null &&conditionBean.getBrand_ids().size()!=0)||
                (conditionBean.getAttributes()!=null && conditionBean.getAttributes().size() != 0)||
                !TextUtils.isEmpty(conditionBean.getPromotion_type())||
                (conditionBean.getCids()!=null&&conditionBean.getCids().size() != 0)){

//            tvFilt.setTextColor(getResources().getColor(R.color.color_333333));
//            Drawable drawble_select=getResources().getDrawable(R.mipmap.shaixuan_select_icon);
//            drawble_select.setBounds(0, 0, drawble_select.getMinimumWidth(), drawble_select.getMinimumHeight());
//            tvFilt.setCompoundDrawables(null,null,drawble_select,null);

        }else {
//            tvFilt.setTextColor(getResources().getColor(R.color.textColor_999));
//            Drawable drawble_select=getResources().getDrawable(R.mipmap.shaixuan_icon);
//            drawble_select.setBounds(0, 0, drawble_select.getMinimumWidth(), drawble_select.getMinimumHeight());
//            tvFilt.setCompoundDrawables(null,null,drawble_select,null);
        }
    }

    @Override
    public void loadFailed() {
        if(swipeRefreshLayout.isRefreshing()){
            swipeRefreshLayout.setRefreshing(false);
        }
        emptyView.setVisibility(View.VISIBLE);
//        llSelect.setVisibility(View.GONE);
    }

    public void setOnOpenDrawerListerner(OnOpenDrawerListerner onOpenDrawerListerner) {
        this.onOpenDrawerListerner = onOpenDrawerListerner;
    }

    private OnOpenDrawerListerner onOpenDrawerListerner;

    public interface OnOpenDrawerListerner{
        public void onOpenListerner(SearchGoodBean.DataBean dataBean);

        public void onRefreshCondition(SearchGoodBean.DataBean dataBean,boolean isFirst);
    }
}
